<template>
  <div>
    <el-button @click="onShow">设置</el-button>
    <el-popover v-model="show" trigger="manual" width="800">
      <el-transfer v-model="resultData" :data="datas" target-order="push" :titles="['字段','显示']"></el-transfer>
      <el-button @click="onSave">保存</el-button>
      <el-button @click="show=false">取消</el-button>
    </el-popover>
  </div>
</template>
<script>
  import {queryFields, recordWrite, table} from '../api/http'
  import {fields2tr} from '../utils/util.js'

  export default {
  name: 'FieldSelector',
  props: {
    model: { type: String, default: '' },
    type: { type: String, default: 'table' }
  },
  data () {
    return {
      show: false,
      id: 0,
      record: [],
      datas: [],
      resultData: []
    }
  },
  methods: {
    onShow: function () {
      console.info('onShow')
      this.show = true
      this.getApiData()
      // this.timeInterval = setInterval(() => {
      //   this.getApiData()
      // }, 1000)
    },
    getApiData: function () {
      let self = this
      let uid = localStorage.getItem('uuid')
      queryFields(this.model).then(
        function (response) {
          self.result = response.result
          let fields = self.result.fields
          self.datas = fields2tr(fields)
        },
        function () {}
      )
      table('mobile.model', {
        domain: [['model', '=', self.model]],
        fields: 'field_table,field_record,id'
      }).then(
        function (response) {
          let result = response.result
          let records = result.record
          let record = records[Object.keys(records)[0]]
          self.id = record.id.value
          let rd = []
          if (self.type === 'table') { rd = JSON.parse(record.field_table.value) } else { rd = JSON.parse(record.field_record.value) }
          self.resultData = []
          for (let i of rd) {
            self.resultData.push(Object.keys(i)[0])
          }
        },
        function (error) {
          self.$log.push(error)
        }
      )
    },
    onSave: function () {
      let self = this
      let value = []
      for (let i = 0; i < self.resultData.length; i++) {
        let fn = self.resultData[i]
        let fi = self.result.fields[fn]
        let ff = {}
        ff[fn] = fi.string
        value.push(ff)
      }
      let val = {}
      let uid = localStorage.getItem('uuid')
      if (self.type === 'table') {
        val = { id: self.id, field_table: JSON.stringify(value), res_users_id: uid }
      } else {
        val = { id: self.id, field_record: JSON.stringify(value), res_users_id: uid }
      }
      recordWrite('mobile.model', val).then(
        function (response) {
          self.show = false
        },
        function (error) {}
      )
    }
  }
}
</script><style scoped>
</style>
